package com.ruoyi.framework.security.jwt;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.properties.SecurityConfigProperties;
import com.ruoyi.framework.security.web.authentication.CustWebAuthenticationDetailsSource;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Nonnull;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final TokenService tokenService;
    private final SecurityConfigProperties securityConfigProperties;


    private final PathMatcher pathMatcher = new AntPathMatcher();


    public JwtAuthenticationTokenFilter(TokenService tokenService, SecurityConfigProperties securityConfigProperties) {
        this.tokenService = tokenService;
        this.securityConfigProperties = securityConfigProperties;
    }

    protected String getReqPath(HttpServletRequest request) {
        String url = request.getRequestURI();
        // 若有contextPath,则切出来
        if (org.springframework.util.StringUtils.hasLength(request.getContextPath())) {
            String contextPath = request.getContextPath();
            int index = url.indexOf(contextPath);
            if (index != -1) {
                url = url.substring(index + contextPath.length());
            }
        }
        return url;
    }

    @Override
    protected void doFilterInternal(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull FilterChain chain)
            throws ServletException, IOException {
        Set<String> jwtAnonymousUrls = securityConfigProperties.getJwtAnonymousUrls();
        if (Objects.nonNull(jwtAnonymousUrls) && !jwtAnonymousUrls.isEmpty()) {
            String url = getReqPath(request);
            boolean anyMatch = jwtAnonymousUrls.parallelStream()
                    .anyMatch(jwtAnonymousUrl -> pathMatcher.match(url, jwtAnonymousUrl));
            if (anyMatch) {
                chain.doFilter(request, response);
                return;
            }
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new CustWebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
